package com.edu.dao.impl;

import com.edu.dao.CategoriesDao;
import com.edu.entity.CategoryEntity;
import com.edu.entity.UserEntity;
import com.edu.utils.DatabaseManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * com.edu.dao.impl
 * 2024/7/4 21:03
 *
 * @author Fancy
 * @version 1.0
 */
public class CategoriesDaoImpl implements CategoriesDao {
    private Connection connection;

    public CategoriesDaoImpl() {
        try {
            this.connection = DatabaseManager.getInstance().getConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    @Override
    public CategoryEntity getCategoryById(int categoryId) {
        try {
            String sql = "SELECT * FROM Category WHERE category_id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, String.valueOf(categoryId));
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                // Create and return User object
                return new CategoryEntity(resultSet.getInt("category_id"), resultSet.getString("name"), resultSet.getInt("parent_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<CategoryEntity> getAllCategory() {
        try {
            String sql = "SELECT * FROM Category";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            List<CategoryEntity> categoryEntities = new LinkedList<>();
            while (resultSet.next()) {
                // Create and return User object
                CategoryEntity categoryEntity = new CategoryEntity(
                        resultSet.getInt("category_id"),
                        resultSet.getString("name"),
                        resultSet.getInt("parent_id"));
                categoryEntities.add(categoryEntity);
            }
            return categoryEntities;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
